package com.ktgj.customer.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * Created by lilang on 2017/4/28.
 */

public class HttpPostUtil {
    private static final int BUFFER = 1024;
    static final Log log = LogFactory.getLog(RsaUtil.class);

    public static String post(String url, String xmlObj) {
        String result = null;

        HttpPost httpPost = new HttpPost(url);

        //得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);

        try {
            HttpResponse response = HttpClients.custom()
                    .build().execute(httpPost);
            HttpEntity entity = response.getEntity();
            entity.getContent();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            log.error("http post request error: ", e);
        } finally {
            httpPost.abort();
        }
        return result;
    }
    public static String post(String url, Map<String,String> paramsMap) throws Exception {
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(),entry.getValue() ));
        }
        SimpleHttpResponse response = postFormWithTimeOut(url,params,"UTF-8",null,15000);
        return response.getEntityString();
    }
    /**
     * 请求超时时间 2s
     * 链接超时时间 2s
     * 读取响应超时时间 15s
     * @param url 请求地址
     * @param nvps 请求参数
     * @param encodetype 编码
     * @param headers 请求头
     * @param socketTimeout 读取超时时间
     * @return 返回请求响应
     */
    public static SimpleHttpResponse postFormWithTimeOut(String url, List<NameValuePair> nvps, String encodetype, List<String[]> headers, int socketTimeout) throws Exception{
        log.info("发送POST请求给 url："+url+" socketTimeout:{}"+ socketTimeout);
        if(socketTimeout == 0){
            socketTimeout = 60000;
        }
        HttpClient httpclient = HttpClients.createDefault();
        RequestConfig config=RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(socketTimeout).build();
        if(url.startsWith("https://")){
            try {
                javax.net.ssl.SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    //信任所有证书
                    @Override
                    public boolean isTrusted(
                            java.security.cert.X509Certificate[] chain,
                            String authType)
                            throws java.security.cert.CertificateException {
                        return true;
                    }
                }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String data = "";
        SimpleHttpResponse httpResponse=null;
        try {
            HttpPost httppost = new HttpPost(url);
            if (null != headers) {
                for (String[] header : headers) {
                    httppost.addHeader(header[0], header[1]);
                }
            }
            httppost.setEntity(new UrlEncodedFormEntity(nvps,encodetype));
            httppost.setConfig(config);
            log.info("url：{}"+ httppost.getURI());
            //log.info("postData:{}", java.net.URLDecoder.decode(EntityUtils.toString(httppost.getEntity(),encodetype)));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            data = EntityUtils.toString(response.getEntity(), encodetype);
            log.info("发送 URL：{}"+url);
            httpResponse=isRequestSuccess(statusCode)?new SimpleHttpResponse(statusCode, data, (String)null):new SimpleHttpResponse(statusCode, (String)null, response.getStatusLine().getReasonPhrase());
            EntityUtils.consume(resEntity);
        } catch (Exception ex) {
            httpclient.getConnectionManager().shutdown();
            ex.printStackTrace();
            log.error("Exception ：{}",ex);
            throw new Exception("http请求异常：{}", ex);
        }
        return httpResponse;
    }
    /**
     * 数据解压缩
     *
     * @param is 压缩文件刘
     * @param os 输出流
     */
    public static void decompress(InputStream is, OutputStream os)
            throws IOException {
        GZIPInputStream gis = new GZIPInputStream(is);
        //GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(is));
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = gis.read(data, 0, BUFFER)) != -1) {
            os.write(data, 0, count);
        }
        gis.close();
    }
    public static boolean isRequestSuccess(int statusCode) {
        return statusCode == 200;
    }
}
